/**
 * Created by Dave on 2017/3/11.
 */
module.exports=function (obj) {
        obj.optObject=function(path){
            var d=this;
            for(var id in path){
                if(d.hasOwnProperty(path[id]))
                    d=d[path[id]];
                else
                    return null;
            }
            return d;
        }
        obj.getFirstObjectKey = function (selector) {
            var arr = this;
            for (var key=0;key<this.length;key++) {
                if (arr[key] != null && selector(arr[key]))
                    return key;
            }
            return null;
        }
        obj.getFirstObject=function(selector) {
            var arr = this;
            var key = this.getFirstObjectKey(selector);
            if (key)
                return arr[key];
            return null;
        }

        obj.getKeys = function (selector) {
            var arr = this;
            return this.getObjectFields(selector, function (e, key) {
                return key;
            });
        }

        obj.getObjectFields = function (selector,getter) {
            var arr = this;
            var res = [];
            for (var key=0;key<this.length;key++) {
                if (selector(arr[key]))
                    res.push(getter(arr[key], key));
            }
            return res;
        }

        obj.getMaxIndex=function(comparator){
            var arr = this;
            var max=null,id=null;
            if(arr.length>0){
                max=arr[0];
                id=0;
            }
            for (var key=0;key<this.length;key++) {
                if (comparator(max,arr[key])<=0){
                    id=key;
                    max=arr[key];
                }
            }
            return id;
        }

        obj.getMax=function(comparator){
            var key=this.getMaxIndex(comparator);
            return key==null?null:this[key];
        }

        obj.deleteObject = function (selector) {
            var arr = this;
            var key = null;
            do {
                key = this.getFirstObjectKey(selector);
                if (key != null) {
                    arr.splice(key, 1);//delete arr[key];//删除
                }
            } while (key != null);
        }
        obj.checkModel=function(model){
            for(var name in model){
                var checkMethod=model[name];
                var res=this.hasOwnProperty(name);
                if(!res)
                    return name;
                if(typeof checkMethod =="function"){
                    res=checkMethod(this[name]);
                }else{
                    res=this[name]!=null&&this[name].trim()!="";
                }
                if(!res)
                    return name;
            }
            return null;
        }
    }